package cn.conac.rc.ofs.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.ofs.entity.VAuditList2Entity;
import cn.conac.rc.ofs.repository.VAuditList2Repository;
import cn.conac.rc.ofs.vo.VAuditList2Vo;

/**
 * VAuditList2Service类
 *
 * @author serviceCreator
 * @date 2016-12-26
 * @version 1.0
 */
@Service
public class VAuditList2Service extends GenericService<VAuditList2Entity, Integer> {

	@Autowired
	private VAuditList2Repository repository;

	/**
	 * 计数查询
	 * @param vo
	 * @return 计数结果
	 */
	public long count(VAuditList2Vo vo){
		return super.count(this.createCriteria(vo));
	}

	/**
	 * 动态查询，分页，排序查询
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<VAuditList2Entity> list(VAuditList2Vo vo) throws Exception {
		try {
			Sort sort = new Sort(new Sort.Order(Direction.ASC, "status"),new Sort.Order(Direction.DESC, "updateTime"));
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<VAuditList2Entity> dc = this.createCriteria(vo);
			return repository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * @param param
	 * @return Criteria
	 */
	private Criteria<VAuditList2Entity> createCriteria(VAuditList2Vo param) {
		Criteria<VAuditList2Entity> dc = new Criteria<>();
		
		if (param.getUserId() != null 
				&& param.getId() != null 
				&&  param.getOrOperFlag() != null 
				&& param.getOrOperFlag().intValue()==1) {
			dc.add(Restrictions.or(Restrictions.eq("userId", param.getUserId(), true),
					Restrictions.eq("id", param.getId(), true)));
		} else {
			// 用户ID
			if (param.getUserId() != null) {
				dc.add(Restrictions.eq("userId", param.getUserId(), true));
			}
			if (null != param.getId()) {
				dc.add(Restrictions.eq("id", param.getId(), true));
			}
		}
		
		if (StringUtils.isNotEmpty(param.getType())) {
			dc.add(Restrictions.eq("type", param.getType(), true));
		}
		if (StringUtils.isNotBlank(param.getName())) {
			dc.add(Restrictions.like("orgName", param.getName(), true));
		}
		if (StringUtils.isNotBlank(param.getStatus())) {
			dc.add(Restrictions.eq("status", param.getStatus(), true));
		}
	
		return dc;
	}

}
